package com.cf.society_management.service;

import com.cf.society_management.mapper.UserMapper;
import com.cf.society_management.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    // 根据ID获取用户
    public User getUserById(int id) {
        return userMapper.findById(id);
    }

    // 登录验证
    public boolean validateUser(String account, String password) {
        User user = findUserByUsername(account);
        // 用户存在且密码匹配
        return user != null && user.getPassword().equals(password);
    }

    // 注册新用户
    public boolean registerUser(String account, String password, String email, String sexy, String introduce) {
        // 检查用户名是否已存在
        if (findUserByUsername(account) != null) {
            return false; // 用户已存在
        }
        // 创建新用户
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        user.setEmail(email);
        user.setSexy(sexy);
        user.setIntroduce(introduce);

        // 保存新用户到数据库
        userMapper.save(user);
        return true;
    }

    // 查找用户名对应的用户
    private User findUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }
}
